"""K8s提取器文件操作工具模块"""

import os
import shutil
from typing import List, Optional
import logging

logger = logging.getLogger(__name__)

def ensure_dir(directory: str) -> bool:
    """
    确保目录存在，如果不存在则创建
    
    Args:
        directory: 目录路径
        
    Returns:
        是否成功创建或目录已存在
    """
    if not os.path.exists(directory):
        try:
            os.makedirs(directory, exist_ok=True)
            logger.debug(f"创建目录: {directory}")
            return True
        except Exception as e:
            logger.error(f"创建目录失败: {directory}, 错误: {str(e)}")
            return False
    return True

def clean_directory(directory: str) -> bool:
    """
    清空目录内容但保留目录
    
    Args:
        directory: 要清空的目录路径
        
    Returns:
        是否成功清空
    """
    if not os.path.exists(directory):
        logger.debug(f"目录不存在，无需清空: {directory}")
        return True
    
    try:
        for item in os.listdir(directory):
            item_path = os.path.join(directory, item)
            if os.path.isdir(item_path):
                shutil.rmtree(item_path)
            else:
                os.remove(item_path)
        logger.debug(f"目录已清空: {directory}")
        return True
    except Exception as e:
        logger.error(f"清空目录失败: {directory}, 错误: {str(e)}")
        return False

def get_relative_path(path: str, base_path: str) -> str:
    """
    获取相对路径
    
    Args:
        path: 完整路径
        base_path: 基准路径
        
    Returns:
        相对于base_path的相对路径
    """
    try:
        return os.path.relpath(path, base_path)
    except ValueError as e:
        logger.error(f"获取相对路径失败: {str(e)}")
        return os.path.basename(path)

def find_files(directory: str, extensions: Optional[List[str]] = None, recursive: bool = True) -> List[str]:
    """
    查找指定目录下所有符合扩展名的文件
    
    Args:
        directory: 要查找的目录
        extensions: 文件扩展名列表，如['.yaml', '.yml']
        recursive: 是否递归查找子目录
        
    Returns:
        找到的文件路径列表
    """
    if extensions is None:
        extensions = ['.yaml', '.yml', '.json']
        
    files = []
    
    # 确保扩展名都以.开头
    normalized_extensions = [
        ext if ext.startswith('.') else f'.{ext}' for ext in extensions
    ]
    
    if not os.path.isdir(directory):
        logger.error(f"目录不存在: {directory}")
        return files
    
    for root, _, filenames in os.walk(directory):
        for filename in filenames:
            _, ext = os.path.splitext(filename)
            if ext.lower() in normalized_extensions:
                files.append(os.path.join(root, filename))
        if not recursive:
            break
            
    logger.debug(f"在{directory}中找到{len(files)}个文件")
    return files

def copy_file(src: str, dst: str, overwrite: bool = True) -> bool:
    """
    复制文件
    
    Args:
        src: 源文件路径
        dst: 目标文件路径
        overwrite: 是否覆盖已存在的目标文件
        
    Returns:
        是否成功复制
    """
    if not os.path.exists(src):
        logger.error(f"源文件不存在: {src}")
        return False
        
    if os.path.exists(dst) and not overwrite:
        logger.debug(f"目标文件已存在，不覆盖: {dst}")
        return True
        
    try:
        # 确保目标目录存在
        dst_dir = os.path.dirname(dst)
        ensure_dir(dst_dir)
        
        shutil.copy2(src, dst)
        logger.debug(f"文件已复制: {src} -> {dst}")
        return True
    except Exception as e:
        logger.error(f"复制文件失败: {src} -> {dst}, 错误: {str(e)}")
        return False
